package com.qianxp.designparttern.template;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qianxp
 * @createTime 2019/11/17 0017
 */
public class CJdbcTemplate {

    private DataSource dataSource;

    public CJdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    private PreparedStatement getPreparedStatement(Connection con, String sql,Object[] vals) throws SQLException {
        PreparedStatement pstm =  con.prepareStatement(sql);
        for (int i=0;i<vals.length;i++) {
            pstm.setObject(i,vals[i]);
        }
        return pstm;
    }

    private void closeResult(ResultSet resultSet) throws SQLException {
        resultSet.close();
    }

    private void closePreparedStatement(PreparedStatement preparedStatement) throws SQLException {
        preparedStatement.close();
    }

    private void closeConnection(Connection con) throws SQLException {
        con.close();
    }


    /**
     * <p>
     * 1.get con
     * 2.get ps
     * 3.execute query
     * 4.get rs
     * 5.close rs
     * 6.close ps
     * 7.close con
     * </p>
     *
     * @return
     */
    public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[] vals) throws Exception {
        Connection con = this.getConnection();
        PreparedStatement pstm = getPreparedStatement(con,sql,vals);
        ResultSet rs = pstm.executeQuery();
        List<Object> list = new ArrayList<>();
        while (rs.next()) {
            list.add(rowMapper.processResult(rs));
        }
        closeResult(rs);
        closePreparedStatement(pstm);
        closeConnection(con);
        return list;
    }

}
